﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Affirma.ThreeSharp;
using Affirma.ThreeSharp.Model;
using Affirma.ThreeSharp.Query;

namespace Yonkly.Utility
{
    public static class AmazonHelper
    {
        private static ThreeSharpConfig config;
        private static IThreeSharp service;
        //  private String basePath;

        // Insert your AWS access keys here.
        private static string awsAccessKeyId = Globals.AmazonAccessKeyId;
        private static string awsSecretAccessKey = Globals.AmazonSecretAccessKey;
        //private ConfigHelper settings = new ConfigHelper();
        //public const string bucketName =  //"justine";
        //public delegate void UploadFileDelegate(String bucketName, String filename, string rawdata, byte[] bytes);
        //public static UploadFileDelegate uploadFileDelegate;

        static AmazonHelper()
        {
            //uploadFileDelegate = new UploadFileDelegate(UploadFile);//this.
            config = new ThreeSharpConfig();
            config.AwsAccessKeyID = awsAccessKeyId;
            config.AwsSecretAccessKey = awsSecretAccessKey;
            config.ConnectionLimit = 40;
            config.IsSecure = true;

            // It is necessary to use the SUBDOMAIN CallingFormat for accessing EU buckets
            config.Format = CallingFormat.SUBDOMAIN;
            service = new ThreeSharpQuery(config);
        }

        public static void Delete(string key)
        {

            service.ObjectDelete(new ObjectDeleteRequest(Globals.AmazonBucketName, key));
        }


        public static string GetFileUrl(string fileName)
        {
            ThreeSharpQuery tsq = new ThreeSharpQuery(config);
            Affirma.ThreeSharp.Model.UrlGetRequest req = new Affirma.ThreeSharp.Model.UrlGetRequest(Globals.AmazonBucketName, fileName);
            req.ExpiresIn = 100 * 60 * 1000;
            string querystring = tsq.UrlGet(req).StreamResponseToString();

            return querystring;
        }

        #region "AWS Upload Code"

        public static void UploadFile(String bucketName, String filename, String rawdata, byte[] bytes)
        {
            // The first thing we need to do is check for the presence of a Temporary Redirect.  These occur for a few
            // minutes after an EU bucket is created, while S3 creates the DNS entries.  If we get one, we need to upload
            // the file to the redirect URL

            String redirectUrl = null;
            using (BucketListRequest testRequest = new BucketListRequest(bucketName))
            {
                testRequest.Method = "HEAD";
                using (BucketListResponse testResponse = service.BucketList(testRequest))
                {
                    if (testResponse.StatusCode == System.Net.HttpStatusCode.TemporaryRedirect)
                    {
                        redirectUrl = testResponse.Headers["Location"].ToString() + filename.Replace(' ', '_');
                    }
                }
            }
            using (ObjectAddRequest request = new ObjectAddRequest(bucketName, filename.Replace(' ', '_')))
            {
                request.Headers.Add("x-amz-acl", "public-read-write");//public-read-write// Properties.Settings.Default.AclType
                request.Key = filename;

                if (bytes != null)
                {
                    request.LoadStreamWithBytes(bytes);
                }
                else if (rawdata != null)
                {
                    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                    request.LoadStreamWithBytes(encoding.GetBytes(rawdata));
                    // request.LoadStreamWithString(rawdata);
                }

                if (redirectUrl != null)
                {
                    request.RedirectUrl = redirectUrl;
                }

                using (ObjectAddResponse response = service.ObjectAdd(request))
                { }

            }

            // this.listBoxObjects.Invoke(listBucketDelegate, new object[] { bucketName });
        }
        #endregion

    }
}
